package club.zykeji.ddns.aliddnsserver.controller;

import club.zykeji.ddns.aliddnsserver.common.Result;
import club.zykeji.ddns.aliddnsserver.util.DnsUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Create by 丶TheEnd on 2020/5/5.
 * @author TheEnd
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@RestController
@RequestMapping("/d-dns")
public class DDNSController {

    @Autowired
    private DnsUtil dnsUtil;

    /**
     * 获取自己的公网IP
     * @param request
     * @return
     */
    @GetMapping("/ip/my")
    public Result getMyIp(HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        if (StrUtil.isBlank(remoteHost)) {
            return Result.error();
        }
        return Result.success(remoteHost);
    }

    /**
     * 获取自己的公网IP
     * @param request
     * @return
     */
    @GetMapping("/ip/my/string")
    public String getMyIpString(HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        if (StrUtil.isBlank(remoteHost)) {
            return "error";
        }
        return remoteHost;
    }

    /**
     * 绑定DDNS
     * @param host
     * @param value
     * @return
     */
    @GetMapping("/dns/bind")
    public Result bindDDNS(@RequestParam("host") String host,
                           @RequestParam("value") String value) {

        String ip = dnsUtil.getIpByHost(host);

        if (StrUtil.hasBlank(ip)) {
            return Result.error("查询出错或域名不存在,请检查您的域名");
        }

        if (value.equals(ip)) {
            return Result.success("当前已是最新");
        }

        String result = dnsUtil.updateBindIp(host, value);
        if ("success".equals(result)) {
            return Result.success();
        }

        return Result.error();

    }

    /**
     * 获取域名当前绑定的IP
     * @param host
     * @return
     */
    @GetMapping("/dns/bind/current")
    public Result getCurrentBinding(@RequestParam("host") String host) {
        String ip = dnsUtil.getIpByHost(host);
        if (StrUtil.hasBlank(ip)) {
            return Result.error("查询出错或域名不存在,请检查您的域名");
        }
        return Result.success(ip);
    }

}
